package cn.study.es;

import cn.study.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StudentSearche {
    //用来执行查询的工具对象
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    //按照姓名搜索
    public List<Student> findByName(String name){
        //创建Criteria对象
        Criteria c = new Criteria("name");
        //在name字段搜索指定的关键词
        c.is(name);
        return exec(c,null);
    }

    //按照日期范围搜索，并添加分页
    public List<Student> findByBirthDate(String from, String to, Pageable pageable){
        //创建Criteria对象
        Criteria c = new Criteria("birthDate");
        //在name字段搜索指定的关键词
        c.between(from,to);
        return exec(c,pageable);
    }

    private List<Student> exec(Criteria c, Pageable pageable) {
        //使用CriteriaQuery封装Criteria对象
        CriteriaQuery q = new CriteriaQuery(c);
        if(pageable != null){
            q.setPageable(pageable);
        }
        //使用elasticsearchOperations对象进行搜索，并把搜索结果封装成student对象（默认返回是一个json串）
        SearchHits<Student> search = elasticsearchOperations.search(q, Student.class);
        List<Student> list = new ArrayList<>();
        for (SearchHit<Student> sh : search) {
            list.add(sh.getContent());
        }
        return list;
    }
}
